package com.yonhee.datastructure.circleLinkedList;

import java.util.Iterator;

/**
 * 双向循环链表
 */
public class DoublyLinkedListSentinel implements Iterable<Integer> {

    /**
     * 节点类
     */
    static class Node {
        Node prev;  // 上一个节点
        Node next;  // 下一个节点
        int value;

        public Node(Node prev, Node next, int value) {
            this.prev = prev;
            this.next = next;
            this.value = value;
        }
    }

    private Node sentinel = new Node(null, null, -1);

    public DoublyLinkedListSentinel() {
        sentinel.prev = sentinel;
        sentinel.next = sentinel;
    }

    public void addFirst(int val) {
        Node head = sentinel;
        Node next = sentinel.next;
        Node cur = new Node(head, next, val);
        head.next = cur;
        next.prev = cur;
    }

    public void removeFirst() {
        Node firstNode = sentinel.next;
        if (firstNode == sentinel) {
            throw new IllegalArgumentException("list is empty");
        }
        Node head = sentinel;
        Node next = firstNode.next;

        head.next = next;
        next.prev = head;
    }

    public void addLast(int val) {
        Node tail = sentinel;
        Node prev = sentinel.prev;
        Node cur = new Node(prev, tail, val);
        prev.next = cur;
        tail.prev = cur;
    }

    public void removeLast() {
        Node tail = sentinel;
        Node removed = sentinel.prev;
        if (removed == sentinel) {
            throw new IllegalArgumentException("list is empty");
        }
        Node prev = removed.prev;
        prev.next = tail;
        tail.prev = prev;
    }

    public void removeByValue(int val) {
        Node removed = findByVal(val);
        if (removed == null) {
            throw new IllegalArgumentException("list not has the val");
        }
        Node prev = removed.prev;
        Node next = removed.next;
        prev.next = next;
        next.prev = prev;
    }

    public void insert(int index, int val) {
    }

    public void remove(int index) {
    }

    /**
     *
     * @return
     */
    private Node findByVal(int val) {
        Node p = sentinel.next;
        while (p != sentinel) {
            if (p.value == val) {
                return p;
            }
            p = p.next;
        }
        return null;
    }

    private IllegalArgumentException illegalArgument(int index) {
        return new IllegalArgumentException(String.format("index %s 非法参数", index));
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {

            private Node p = sentinel.next;

            @Override
            public boolean hasNext() {
                return p != sentinel;
            }

            @Override
            public Integer next() {
                int value = p.value;
                p = p.next;
                return value;
            }
        };
    }
}
